<?
require_once('functions.php');

function GetProducts()
{
        $conn = GetConnection();
        return $conn->query('SELECT * FROM 2012WP_Products');
}
function BlankProduct()
{
        return array('ProductName'=>null,'Price'=>null, 'Description'=>null, 'ProductTypes_id'=>null, 'Quantity'=>null, 'created_at'=>null,'updated_at'=>null,'id'=>null);
}
function GetProduct($id)
{
        $conn = GetConnection();
        $sql = "SELECT * FROM 2012WP_Products WHERE id=$id";
        $results = $conn->query($sql);
        //echo $sql;
        $row = $results->fetch_assoc();
        $conn->close();
        return $row;
}
function SaveProduct(&$row)
{
        $conn = GetConnection();
        $row2 = EscapeRow($row, $conn);
        if(empty($row['id']))
        {
                $sql =  "Insert 2012WP_Products (ProductName, Price, Description, 2012WP_ProductTypes_id, Quantity, created_at) "
                        .       " Values ('$row2[ProductName]','$row2[Price]', '$row2[Description]', '$row2[ProductTypes_id]', '$row2[Quantity]', NOW() ) ";
        }else{
                $sql =  "UPDATE 2012WP_Products "
                        .       "Set ProductName='$row2[ProductName]', Price='$row2[Price]', Description='$row2[Description]',  2012WP_ProductTypes_id='$row2[ProductTypes_id]', Quantity='$row2[Quantity]' "
                        .       "WHERE id=$row2[id] ";
        }
        $results = $conn->query($sql);
        //echo $sql;
        $error = $conn->error;
        if(empty($row['id']) && empty($error))
        {
                $row['id'] = $conn->insert_id;
        }
        $conn->close();
       
        return $error == '' ? true : array('SQL Error' => $error);
}
function DeleteProduct($id)
{
        $conn = GetConnection();
        $sql =  "DELETE FROM 2012WP_Products WHERE id=$id";
        $results = $conn->query($sql);
        //echo $sql;
        $error = $conn->error;
        $conn->close();
       
        return $error == '' ? true : array('SQL Error' => $error);
}
function ValidateProduct($row)
{
        $errors = array();
        if(empty($row['ProductName'])) $errors['ProductName'] = 'Product Name is required';
        if(empty($row['Price'])) $errors['Price'] = 'Price is required';
		if(!is_numeric($row['Price'])) $errors['Price'] = 'Price must be a number';
		if(empty($row['Description'])) $errors['Description'] = 'Description is required';
        if(!is_numeric($row['ProductTypes_id'])) $errors['ProductTypes_id'] = 'ProductTypes_id must be a number';
        if(empty($row['ProductTypes_id'])) $errors['ProductTypes_id'] = 'ProductTypes_id is required';
		if(!is_numeric($row['Quantity'])) $errors['Quantity'] = 'Quantity must be a number';
        if(empty($row['Quantity'])) $errors['Quantity'] = 'Quantity is required';
       
        return count($errors) == 0 ? true : $errors;
}
